package pzc.context.mail;

import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

import pzc.context.util.ContextBinder;

public class MailContext {

	private static Logger logger = Logger.getLogger(MailContext.class.getName());

	public static void initContext(String jndiName, String smtpHost, String smptPort, final String userId, final String password,
			boolean useAuth) throws Exception {

		Properties props = System.getProperties();

		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.port", smptPort);
		props.put("mail.smtp.user", userId);
		if (useAuth) {
			props.setProperty("mail.smtp.auth", "true");
		} else {
			props.setProperty("mail.smtp.auth", "false");
		}

		Session session = Session.getDefaultInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userId, password);
			}
		});

		ContextBinder.bind(jndiName, session);

		logger.info("Mail Session '" + jndiName + "' is bound");
	}

}
